/**
Copyright (c) 2008 New Gonzo <john@newgonzo.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/


﻿package com.newgonzo.cannonball.browser.context
{
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.display.DisplayObject;
	import flash.net.*;
	import flash.utils.Dictionary;
	
	import com.adobe.net.URI;

	import com.newgonzo.commons.logging.Log;
	import com.newgonzo.commons.logging.ILogger;
	
	import com.newgonzo.cannonball.w3c.dom.*;
	
	import com.newgonzo.cannonball.dom.*;
	import com.newgonzo.cannonball.dom.css.*;
	import com.newgonzo.cannonball.dom.traversal.*;
	import com.newgonzo.cannonball.css.*;
	import com.newgonzo.cannonball.dom.*;
	import com.newgonzo.cannonball.dom.html.*;
	
	import com.newgonzo.cannonball.browser.loading.*;
	import com.newgonzo.cannonball.browser.rendering.*;
	import com.newgonzo.cannonball.browser.dom.*;
	import com.newgonzo.cannonball.browser.events.*;
	import com.newgonzo.cannonball.browser.actions.*;
	
	public class AbstractContext extends EventDispatcher
	{	
		protected static const log:ILogger = Log.getLogger(AbstractContext);
		
		// used for generated names
		private static var contextCount:uint = 0;
		
		private var contextName:String;
		private var contextView:IView;
		private var contextLoader:ILoader;
		private var contextStyle:IStyle;
		private var rootContext:IContext;
		private var parentContext:IContext;
		private var contextChildren:Dictionary;
		private var contextWindow:IWindow;
		private var contextRendering:IRendering;
		
		private var activeDocument:IDocument;
		
		private var contextActions:Array;
		private var actionHandlers:Dictionary;
		
		private var navigateAction:IMacroAction;
		
		private var dom:DOMImplementation;
		
		public function AbstractContext()
		{
			contextCount++;
			
			contextChildren = new Dictionary();
			contextActions = new Array();
			actionHandlers = new Dictionary();
			
			dom = new DOMImplementation();
			
			contextName = "context" + contextCount;
		}
		
		public function get name():String
		{
			return contextName;
		}
		
		public function set name(value:String):void
		{
			contextName = value;
		}
		
		public function get document():IDocument
		{
			return activeDocument;
		}
		
		public function get loader():ILoader
		{
			if(!contextLoader)
			{
				contextLoader = createLoader();
			}
			
			return contextLoader;
		}
		
		public function get view():IView
		{
			if(!contextView)
			{
				contextView = createView();
			}
			
			return contextView;
		}
		
		public function set view(value:IView):void
		{
			contextView = value;
		}
		
		public function get style():IStyle
		{
			if(!contextStyle)
			{
				contextStyle = createStyle();
			}
			
			return contextStyle;
		}
		
		public function set style(value:IStyle):void
		{
			contextStyle = value;
		}
		
		public function get root():IContext
		{
			if(!rootContext)
			{
				var context:IContext = this as IContext;
				
				while(context.parent)
				{
					context = context.parent;
				}
				
				rootContext = context;
			}
			
			return rootContext;
		}
		
		public function set parent(value:IContext):void
		{
			if(parentContext)
			{
				throw new Error("Context parent cannot be reset.");
			}
			
			parentContext = value;
			// reset cached root
			rootContext = null;
		}
		
		public function get parent():IContext
		{
			return parentContext;
		}
		
		public function get window():IWindow
		{
			if(!contextWindow)
			{
				contextWindow = createWindow();
			}
			
			return contextWindow;
		}
		
		public function get rendering():IRendering
		{
			if(!contextRendering)
			{
				contextRendering = createRendering();
			}
			
			return contextRendering;
		}
		
		public function navigate(url:String):IAction
		{
			log.info("AbstractContext navigating to " + arguments);
			
			// If there's a pending navigate action, cancel it
			if(navigateAction)
			{
				navigateAction.removeEventListener(ActionEvent.COMPLETE, navigateActionComplete);
				//navigateAction.cancel();
			}
			
			navigateAction = execute(ActionType.NAVIGATE, url) as IMacroAction;
			
			navigateAction.addEventListener(ActionEvent.RESULT, documentLoadActionComplete);
			navigateAction.addEventListener(ActionEvent.COMPLETE, navigateActionComplete);
		
			dispatchEvent(new ContextEvent(ContextEvent.NAVIGATE, navigateAction));
			
			return navigateAction;
		}
		
		public function open(url:String = "", name:String = ""):IContext
		{
			log.info("AbstractContext opening " + arguments);
			
			var newContext:IContext;
			
			if(!contextChildren[name])
			{
				newContext = createContext();
				newContext.name = name;
				newContext.parent = this as IContext;
				contextChildren[name] = newContext;
			} 
			else
			{
				newContext = contextChildren[name] as IContext;
			}
			
			var action:IAction;
			
			if(url.length)
			{
				action = newContext.navigate(url);
			}
			
			dispatchEvent(new ContextEvent(ContextEvent.OPEN, action));
			
			return newContext;
		}
		
		public function load(item:Object):IAction
		{
			return execute(ActionType.LOAD, item);
		}
		
		public function activate(item:Object):IAction
		{
			return execute(ActionType.ACTIVATE, item);
		}
				
		public function setHandler(type:String, handler:*):void
		{
			actionHandlers[type] = handler;
		}
		
		public function getHandler(type:String):IActionHandler
		{
			var actionHandler:IActionHandler;
			var handler:* = actionHandlers[type];
			
			if(handler is Class)
			{
				actionHandler = new (handler as Class)() as IActionHandler;
			}
			else
			{
				actionHandler = actionHandlers[type] as IActionHandler;
			}
			
			return actionHandler;
		}
		
		public function execute(type:String, data:Object = null):IAction
		{
			var action:IAction = createAction(type, data);
			executeAction(action);
			return action;
		}
		
		protected function executeAction(action:IAction):void
		{
			log.info("AbstractContext executing " + arguments);
			
			if(action.complete || contextActions.indexOf(action) != -1)
			{
				return;
			}
			
			contextActions.push(action);
			action.addEventListener(ActionEvent.COMPLETE, actionComplete);
			
			var handler:IActionHandler = getHandler(action.type);
			
			if(handler)
			{
				action.handler = handler;
				action.execute();
				dispatchEvent(new ContextEvent(ContextEvent.EXECUTE, action));
			}
		}
		
		protected function createAction(type:String, data:Object = null):IAction
		{
			var action:IAction;
			
			switch(type)
			{
				case ActionType.NAVIGATE:
					action = new MacroAction(type, this as IContext, data);
					break;
					
				default:
					action = new Action(type, this as IContext, data);
					break;
			}
			
			return action;
		}
		
		protected function createWindow():IWindow
		{
			return null;
		}
		
		protected function createContext():IContext
		{
			return null;
		}
		
		protected function createStyle():IStyle
		{
			return null;
		}
		
		protected function createView():IView
		{
			return null;
		}
		
		protected function createLoader():ILoader
		{
			return null;
		}
		
		protected function createRendering():IRendering
		{
			return null;
		}
		
		protected function renderDocument():void
		{
			dispatchEvent(new ContextEvent(ContextEvent.RENDER, navigateAction));
			
			style.render(activeDocument);
			rendering.render(activeDocument);
			
			navigateAction.complete = true;
		}
		
		private function actionComplete(event:ActionEvent):void
		{
			var action:IAction = event.currentTarget as IAction;
			action.removeEventListener(ActionEvent.COMPLETE, actionComplete);
			contextActions.splice(contextActions.indexOf(action), 1);
		}
		
		private function navigateActionComplete(event:ActionEvent):void
		{
			navigateAction.removeEventListener(ActionEvent.COMPLETE, navigateActionComplete);
			
			trace("ARRIVE");
			dispatchEvent(new ContextEvent(ContextEvent.ARRIVE, navigateAction));
		
			navigateAction = null;
		}
		
		private function documentLoadActionComplete(event:ActionEvent):void
		{
			event.currentTarget.removeEventListener(ActionEvent.RESULT, documentLoadActionComplete);
			var action:IAction = event.action;
			
			var url:String = action.data as String;
			var xml:XML = new XML(action.result);
			
			trace(xml.toXMLString());
			
			var document:IDocument = dom.createHTMLDocument();//(xml.namespace());
			document.documentURI = url;
			
			(document as IExtendedNode).content = xml;
			
			log.info("Document load complete: " + document);
			
			action.result = document;
			activeDocument = document;
			
			renderDocument();
		}
	}
}